import {storeBindingsBehavior} from "mobx-miniprogram-bindings";
import mall from "@src/store/mall";
import location from "@src/store/location";
import base from "@src/store/base";
import router from "@src/router";

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: location,
    fields: ['auth'],
  }, {
    store: mall,
    fields: ['curLocation', 'userLocation', 'chooseLocation'],
    actions: ['initLocation', 'setStoreId','setAddress']
  }, {
    store: base,
    fields: ['themeColor', 'themeTitleColor']
  }],
  data: {
    keyword: "",
    activeTab: "store",
    source: "cart",
    showTabs: false,
    title: "",
    deliveryType: "",
    originStoreList: [],
    addressList: [],
    storeList: [],
    disableStoreList: []
  },
  methods: {
    onLoad(options) {
      this.initLocation();
      let {deliveryType, showTabs, activeTab} = options;
      showTabs = !(!showTabs || showTabs === 'false');

      if (!activeTab) {
        activeTab = 'store';
      }
      let title = '';
      if (deliveryType === 'EXPRESS') {
        title = '选择快递配送门店'
      } else if (deliveryType === 'SELF_PICKUP') {
        title = '选择取货门店'
      } else if (deliveryType === 'LOCAL') {
        title = '选择同城配送门店'
      } else if (deliveryType === 'LOCAL_SELF_PICKUP') {
        title = '选择同城/自提门店'
      }
      if (!showTabs && activeTab === 'address') {
        title = '请选择收货地址'
      }

      this.setData({deliveryType, showTabs, activeTab, title});
    },

    handleChangeDelivery(e) {
      let type = e.currentTarget.dataset.type;
      let activeTab = 'address';
      if (type === 'SELF_PICKUP') {
        activeTab = 'store';
      }
      this.setData({deliveryType: type, activeTab: activeTab, originStoreList: []})
    },

    handleToAddress(e) {
      let address = e.detail.address;
      let deliveryType = e.detail.deliveryType;
      try {
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.emit('changeAddress', {
          address: address, deliveryType: deliveryType
        });
        // this.setAddress(address,deliveryType)
      } catch (error) {
        console.error("获取evenChannel失败, 修改地址失败", e)
      }
      router.back()
    },

    handleToStore(e) {
      let store = e.detail.store;
      let deliveryType = e.detail.deliveryType;
      const eventChannel = this.getOpenerEventChannel()
      console.info("修改店铺事件 start")
      try {
        let data = {
          store: store,
          deliveryType: deliveryType
        }
        console.info("修改店铺事件", data)
        eventChannel.emit('changeStore', data);
        console.info("修改店铺事件 end")
      } catch (e) {
        console.error("调用修改店铺事件失败", e);
      }
      router.back()
    },
    onPullDownRefresh: function () {
      wx.stopPullDownRefresh();
    }
  }
});
